package com.xzit.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author haoranlu
 * @project IntelliJ IDEA
 */
public class FileUploadServlet extends HttpServlet {

    private String uploadSaveDir;

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*上传文件保存的目录*/
        uploadSaveDir = this.getServletContext().getRealPath("/WEB-INF/uploadFiles/");
        System.out.println("文件保存的真是目录:"+uploadSaveDir);
        /*创建默认属性设置的磁盘文件项工厂对象*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        System.out.println("默认文件临时目录为:" + System.getProperty("java.io.tmpdir"));
        System.out.println(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        /*构建ServletFileUpload组件*/
        ServletFileUpload fileUpload = new ServletFileUpload();
//      设置使用的FileItemFactory
        fileUpload.setFileItemFactory(factory);
        /*设置相关属性*/
        fileUpload.setFileSizeMax(1024*1024*12);
        fileUpload.setSizeMax(1024*1024*12*10);
        fileUpload.setHeaderEncoding("utf-8");
        /*获取FileItemFactory 所有文件项（FileItem）*/
        List<FileItem> itemList = null;
        try {
            itemList = fileUpload.parseRequest(req);
            for (FileItem item : itemList) {
                /*判断是普通表单字段还是文件组件*/
                boolean bool = item.isFormField();
                if (!bool) {  /*如果是文件对象，则进行保存到磁盘*/
                    String fileName = item.getName();/*获取上传文件的真实名称*/
                    System.out.println("文件的名称:"+fileName);
                    System.out.println("字段名称:"+item.getFieldName());
                    System.out.println("文件大小:"+item.getSize());
                    System.out.println("文件类型:"+item.getContentType());
                    File target = new File(uploadSaveDir + System.currentTimeMillis() + fileName);

                    item.write(target);
                }
                item.delete();/*释放item内容主体*/
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
